/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.client.editor.view.hyperlink;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.tree.DefaultMutableTreeNode;
import offset.nodes.client.chooser.view.NodeChooserDialog;
import offset.nodes.client.virtual.model.GetSchemas;
import offset.nodes.client.model.HierarchyTree;
import offset.nodes.client.model.NodeTypes;
import offset.nodes.client.model.PanelContainer;
import offset.nodes.client.model.Server;
import offset.nodes.client.model.SimpleNamespaceRegistry;
import offset.nodes.client.virtual.model.jcr.QName;
import offset.nodes.client.virtual.model.jcr.nodetype.NodeTypeDefinition;
import offset.nodes.client.virtual.model.jcr.nodetype.NodeTypeReader;
import offset.nodes.client.view.SchemaNodeRenderer;
import offset.nodes.client.view.TreeNodeChooserDialog;

/**
 *
 * @author  Walter Lütgenau
 */
public class InternalHyperlinkPanel extends javax.swing.JPanel {

    Server server;
    String reference = null;
    String type = null;
    NodeTypes types;
    PanelContainer container;
    String path = "/";

    /** Creates new form DataHyperlinkPanel */
    public InternalHyperlinkPanel() {
        initComponents();
    }
    
    public void init(PanelContainer container, Server server, NodeTypes types, String path ) {
        this.container = container;
        this.server = server;
        this.types = initTypes();
        this.path = path;
        validateOkButton();
        updateNode();
    }

    protected NodeTypes initTypes() {
        GetSchemas.Request request = new GetSchemas.Request();
        GetSchemas.Response response = null;
        try {
            response = (GetSchemas.Response) server.sendRequest(request);
            InputStream in = new ByteArrayInputStream(response.getSchemaXml().getBytes());
            NodeTypeDefinition[] definitions = NodeTypeReader.read(in);

            return new NodeTypes(definitions);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        nodeLabel = new javax.swing.JLabel();
        nodeTextfield = new javax.swing.JTextField();
        nodeTextfield.getDocument().addDocumentListener(textFieldDocumentListener);
        nodeButton = new javax.swing.JButton();
        valueTabbedPane = new javax.swing.JTabbedPane();
        propertyPanel = new javax.swing.JPanel();
        propertyLabel = new javax.swing.JLabel();
        propertyTextfield = new javax.swing.JTextField();
        propertyButton = new javax.swing.JButton();
        textPanel = new javax.swing.JPanel();
        textLabel = new javax.swing.JLabel();
        textTextfield = new javax.swing.JTextField();

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("offset/nodes/client/editor/view/resources/EditorBundle"); // NOI18N
        nodeLabel.setText(bundle.getString("Hyperlink.Internal.node")); // NOI18N

        nodeButton.setText("...");
        nodeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectNode(evt);
            }
        });

        propertyLabel.setText(bundle.getString("Hyperlink.Page.property")); // NOI18N

        propertyButton.setText("...");
        propertyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectProperty(evt);
            }
        });

        javax.swing.GroupLayout propertyPanelLayout = new javax.swing.GroupLayout(propertyPanel);
        propertyPanel.setLayout(propertyPanelLayout);
        propertyPanelLayout.setHorizontalGroup(
            propertyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(propertyPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(propertyLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(propertyTextfield, javax.swing.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(propertyButton)
                .addGap(105, 105, 105))
        );
        propertyPanelLayout.setVerticalGroup(
            propertyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(propertyPanelLayout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(propertyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(propertyPanelLayout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(propertyTextfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(propertyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(propertyLabel)
                        .addComponent(propertyButton)))
                .addGap(20, 20, 20))
        );

        valueTabbedPane.addTab("Property", propertyPanel);

        textLabel.setText(bundle.getString("Hyperlink.Page.text")); // NOI18N

        javax.swing.GroupLayout textPanelLayout = new javax.swing.GroupLayout(textPanel);
        textPanel.setLayout(textPanelLayout);
        textPanelLayout.setHorizontalGroup(
            textPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(textPanelLayout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addComponent(textLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(textTextfield, javax.swing.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)
                .addGap(173, 173, 173))
        );
        textPanelLayout.setVerticalGroup(
            textPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(textPanelLayout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(textPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textTextfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textLabel))
                .addContainerGap(22, Short.MAX_VALUE))
        );

        valueTabbedPane.addTab("Text", textPanel);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addComponent(valueTabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 484, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(nodeLabel)
                        .addGap(18, 18, 18)
                        .addComponent(nodeTextfield, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(nodeButton)
                        .addGap(19, 19, 19)))
                .addGap(29, 29, 29))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nodeTextfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(nodeButton)
                    .addComponent(nodeLabel))
                .addGap(27, 27, 27)
                .addComponent(valueTabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 89, Short.MAX_VALUE)
                .addGap(55, 55, 55))
        );
    }// </editor-fold>//GEN-END:initComponents
    private void selectNode(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectNode
        try {
            NodeChooserDialog dialog = new NodeChooserDialog(new javax.swing.JFrame(), true, server, path, "*");
            dialog.setLocation(100, 100);
            dialog.setVisible(true);

            if (dialog.getReturnStatus() == NodeChooserDialog.RET_OK) {
                reference = dialog.getUuid();
                type = dialog.getType();
                nodeTextfield.setText(dialog.getPath());
                propertyTextfield.setText(QName.NAME_PROPERTY.getLocalName());
                validateOkButton();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }//GEN-LAST:event_selectNode

    private void selectProperty(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectProperty
        QName typeName = SimpleNamespaceRegistry.getInstance().toQName(type);
        DefaultMutableTreeNode querySchemaNode = HierarchyTree.setupHierarchicalTree(QName.ANY_NAME,
                (NodeTypeDefinition) types.get(typeName), null, types, true, true);
        TreeNodeChooserDialog chooser = new TreeNodeChooserDialog(null, true, querySchemaNode);
        chooser.setCellRenderer(new SchemaNodeRenderer());
        chooser.setVisible(true);
        if (chooser.getReturnStatus() == TreeNodeChooserDialog.RET_OK) {
            DefaultMutableTreeNode selected = chooser.getSelectedNode();
            propertyTextfield.setText(selected.toString());
        }

    }//GEN-LAST:event_selectProperty

    public void setText(String text) {
        textTextfield.setText(text);
    }
    
    protected void updateNode() {
        if (nodeTextfield.getText() != null && nodeTextfield.getText().length() > 0)
            propertyButton.setEnabled(true);
        else
            propertyButton.setEnabled(false);
    }

    class TextFieldDocumentListener implements DocumentListener {

        public void changedUpdate(DocumentEvent e) {
            updateNode();
        }

        public void insertUpdate(DocumentEvent e) {
            updateNode();
        }

        public void removeUpdate(DocumentEvent e) {
            updateNode();
        }
    }
    TextFieldDocumentListener textFieldDocumentListener = new TextFieldDocumentListener();

    
    protected void validateOkButton() {
        if ( textTextfield.getText() != null && textTextfield.getText().length() > 0 && 
                nodeTextfield.getText() != null && nodeTextfield.getText().length() > 0)
            container.enableOkButton(true);
        else
            container.enableOkButton(false);
    }
    
    public InternalHyperlinkInfo getResult() {
        String property = "";
        if (valueTabbedPane.getSelectedComponent() == propertyPanel)
            property = propertyTextfield.getText();
        return new InternalHyperlinkInfo(reference, nodeTextfield.getText(), textTextfield.getText(), property);
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton nodeButton;
    private javax.swing.JLabel nodeLabel;
    private javax.swing.JTextField nodeTextfield;
    private javax.swing.JButton propertyButton;
    private javax.swing.JLabel propertyLabel;
    private javax.swing.JPanel propertyPanel;
    private javax.swing.JTextField propertyTextfield;
    private javax.swing.JLabel textLabel;
    private javax.swing.JPanel textPanel;
    private javax.swing.JTextField textTextfield;
    private javax.swing.JTabbedPane valueTabbedPane;
    // End of variables declaration//GEN-END:variables
}
